// Third View: Get leads
//**************************** GET LEAD MODEL ********************************//

var getLeadModel = new function () {
	this.DisplayThreeStep = ko.observable(false);

	//************ SHOW/HIDE TAB  *************//
	this.ShowPanel1 = ko.observable(false); 	// Import a List of Leads
	this.ShowPanel2 = ko.observable(false); 	// Get Leads from Lead Sellers
	this.ShowPanel3 = ko.observable(false); 	// Set Up Inbound Phone Number
	this.ShowPanel4 = ko.observable(false); 	// Connect a Webform

	// Panels class
	this.Panel1Class = ko.computed(function () {
		return (this.ShowPanel1()) ? "div-show panel" : "div-hide";
	}, this);
	this.Panel2Class = ko.computed(function () {
		return (this.ShowPanel2()) ? "div-show panel" : "div-hide";
	}, this);
	this.Panel3Class = ko.computed(function () {
		return (this.ShowPanel3()) ? "div-show panel" : "div-hide";
	}, this);
	this.Panel4Class = ko.computed(function () {
		return (this.ShowPanel4()) ? "div-show panel" : "div-hide";
	}, this);

	// Expanders class
	this.Expander1Class = ko.computed(function () {
		return (this.ShowPanel1()) ? "expander expander-open" : "expander expander-close";
	}, this);
	this.Expander2Class = ko.computed(function () {
		return (this.ShowPanel2()) ? "expander expander-open" : "expander expander-close";
	}, this);
	this.Expander3Class = ko.computed(function () {
		return (this.ShowPanel3()) ? "expander expander-open" : "expander expander-close";
	}, this);
	this.Expander4Class = ko.computed(function () {
		return (this.ShowPanel4()) ? "expander expander-open" : "expander expander-close";
	}, this);

	// Expanders text class
	this.ExpanderText1Class = ko.computed(function () {
		return (this.ShowPanel1()) ? "expander-open-text" : "expander-close-text";
	}, this);
	this.ExpanderText2Class = ko.computed(function () {
		return (this.ShowPanel2()) ? "expander-open-text" : "expander-close-text";
	}, this);
	this.ExpanderText3Class = ko.computed(function () {
		return (this.ShowPanel3()) ? "expander-open-text" : "expander-close-text";
	}, this);
	this.ExpanderText4Class = ko.computed(function () {
		return (this.ShowPanel4()) ? "expander-open-text" : "expander-close-text";
	}, this);

	// Li Classes
	this.Li1Class = ko.computed(function () {
		return (this.ShowPanel1()) ? "open" : "";
	}, this);
	this.Li2Class = ko.computed(function () {
		return (this.ShowPanel2()) ? "open" : "";
	}, this);
	this.Li3Class = ko.computed(function () {
		if (!data.IsDialIq || data.IsDialIq == null || data.IsDialIq == undefined) {   // Hide Get inbound phone session if user didn't buy Dial IQ
			return "div-hide";
		}
		return (this.ShowPanel3()) ? "open" : "";
	}, this);
	this.Li4Class = ko.computed(function () {
		return (this.ShowPanel4()) ? "open" : "";
	}, this);
	// Expanders click event : Show this panel and close all other panels
	this.Expander1 = function () {
		getLeadModel.ShowPanel2(false);
		getLeadModel.ShowPanel3(false);
		getLeadModel.ShowPanel4(false);

		return (getLeadModel.ShowPanel1()) ? getLeadModel.ShowPanel1(false) : getLeadModel.ShowPanel1(true);
	};
	this.Expander2 = function () {
		getLeadModel.ShowPanel1(false);
		getLeadModel.ShowPanel3(false);
		getLeadModel.ShowPanel4(false);

		return (getLeadModel.ShowPanel2()) ? getLeadModel.ShowPanel2(false) : getLeadModel.ShowPanel2(true);
	};
	this.Expander3 = function () {
		getLeadModel.ShowPanel1(false);
		getLeadModel.ShowPanel2(false);
		getLeadModel.ShowPanel4(false);

		return (getLeadModel.ShowPanel3()) ? getLeadModel.ShowPanel3(false) : getLeadModel.ShowPanel3(true);
	};
	this.Expander4 = function () {
		getLeadModel.ShowPanel1(false);
		getLeadModel.ShowPanel2(false);
		getLeadModel.ShowPanel3(false);

		return (getLeadModel.ShowPanel4()) ? getLeadModel.ShowPanel4(false) : getLeadModel.ShowPanel4(true);
	};

	//**************************** TAB2: LEAD SELLERS  ********************************//
	this.leadSellerList = ko.observableArray();

	this.showCompanyErrMessage = ko.observable(false);
	this.showExpectErrMessage = ko.observable(false);
	this.showExistContractErrMessage = ko.observable(false);

	this.ErrorCompanyMessage = ko.observable("errorMessage");
	this.ErrorExpectMessage = ko.observable("errorMessage");
	this.ErrorExistContractMessage = ko.observable("errorMessage");

	// Company dropdownlist
	this.CompanyOptions = ko.observableArray(data.LeadSellerList);
	this.CompanyIdSelected = ko.observable(data.LeadSellerList[0].Id);

	// Class to represent a row in the table Lead sellers
	function LeadSellerItem(_leadSourceId, _leadSellerId, _leadSeller, _existContract, _expectedCost, _activate) {
		this.Id = _leadSourceId;
		this.LeadSellerId = _leadSellerId;
		this.LeadSellerName = _leadSeller;
		this.ExistContract = _existContract;
		this.Activate = _activate;
		this.ExpectedCost = "$" + formatCurrency("#,##0.00", _expectedCost);

		this.ChooseYes = _existContract;
		this.ChooseNo = !_existContract;
	}

	///////////////////////////// EVENTS //////////////////////////////
	this.AddLeadSeller = function () {
		if (getLeadModel.ValidateLeadSeller()) {
			var leadSellerId = getLeadModel.CompanyIdSelected();
			var leadSellerName = GetCompanyNameById(leadSellerId);

			var expectedPerLead = FormatPrice($('#iptExpectedCost').val());
			var existContract;
			if ($('#rdoYes').attr("checked") == "checked") {
				existContract = true;
			}
			if ($('#rdoNo').attr("checked") == "checked") {
				existContract = false;
			}

			var dataPost = {
				"leadSellerId": leadSellerId,
				"leadSellerName": leadSellerName,
				"expectedCost": expectedPerLead,
				"existContract": existContract
			};
			var urlPost = "/SetUpWizard/AddLeadSeller";

			closePopup();
			openProcess();

			$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
				success: function (returnData, textStatus, jqXHR) {
					if (returnData.Error == undefined || returnData.Error == null) {
						if ((returnData.length > 0) && (returnData[0].LeadSellerId != undefined)) {
							getLeadModel.leadSellerList.removeAll();
							for (var i = 0; i < returnData.length; i++) {
								getLeadModel.leadSellerList.push(new LeadSellerItem(
									returnData[i].LeadSourceId,
									returnData[i].LeadSellerId,
									returnData[i].LeadSeller,
									returnData[i].ExistContract,
									returnData[i].ExpectedCost,
									returnData[i].Activate));
							}
							getLeadModel.ClearForm();
							hideProcess();

							fix_table_cols_height_tableSetup($('.table-leadslistgroup'));
							$('#ddlCompanyList').find("span.jcf-unselectable").html("Select Company");
						}
						else {
							hideProcess();
							showAlertPopup(returnData.toString(), '');
						}
					}
					else {
						hideProcess();
						showPopupError();
					}
				},
				error: function (xhr, status, error) {
					hideProcess();
					showPopupError();
				}
			}); // End ajax post
		}
	};

	this.ClearForm = function () {
		// Set index to default for ddl
		getLeadModel.CompanyIdSelected(data.LeadSellerList[0].Id);
		$("#ddlCompanyList").find('.center').html("Select Company");

		// Reset blank
		$('#iptExpectedCost').val("");
		//$('#iptExpectedCost').val("").removeClass("focus");
		//$('#iptExpectedCost').val("").removeClass("text-active");

		$('#rdoYes').attr("checked", false);
		$('#rdoNo').attr("checked", false);
	};

	// Css Class
	this.ErrorCompanyClass = ko.computed(function () {
		return (this.showCompanyErrMessage()) ? "error-show" : "error-hide";
	}, this);
	this.ErrorExpectClass = ko.computed(function () {
		return (this.showExpectErrMessage()) ? "error-show" : "error-hide";
	}, this);
	this.ErrorExistContractClass = ko.computed(function () {
		return (this.showExistContractErrMessage()) ? "error-show" : "error-hide";
	}, this);

	this.ValidateLeadSeller = function () {
		var validationResult = true;
		// Company
		if (getLeadModel.CompanyIdSelected() == "0") {
			getLeadModel.ErrorCompanyMessage("Please select a Lead Seller");
			getLeadModel.showCompanyErrMessage(true);
			validationResult = false;
		}

		// Expected cost
		var expectedPerLead = $('#iptExpectedCost').val();
		if (!IsDecimal(expectedPerLead)) {
			getLeadModel.ErrorExpectMessage("Enter a valid Expected Cost");
			getLeadModel.showExpectErrMessage(true);
			validationResult = false;
		}
		// Check over flow of Integer number type
		if (parseFloat(expectedPerLead) > 214748) {
			getLeadModel.ErrorExpectMessage("Expected Cost must be less than or equal to 214748");
			getLeadModel.showExpectErrMessage(true);
			validationResult = false;
		}

		// Exist Contract
		if (($('#rdoYes').attr("checked") == undefined) && ($('#rdoNo').attr("checked") == undefined)) {
			getLeadModel.ErrorExistContractMessage("Please select Yes or No");
			getLeadModel.showExistContractErrMessage(true);
			validationResult = false;
		};

		return validationResult;
	};

	this.LeadListClass = ko.computed(function () {
		return (this.leadSellerList().length > 0)
			? "div-show table table2 table-leadslistgroup" : "div-hide table table2 table-leadslistgroup";
	}, this);

	//************************* TAB3: SET UP INBOUND PHONE NUMBER  *****************************//
	////// Area variables //////
	this.localPhones = ko.observableArray([]);
	this.tollPhones = ko.observableArray([]);

	// Limit phones user can get from system
	this.totalLimitPhone = ko.observable(data.InboundNumberCount);

	this.totalFreeLimitPhone = ko.observable(3);

	var iLocalPhone = 0;
	var iTollPhone = 0;

	this.canGetLocal = ko.observable(false);
	this.AddLocalLinkVisible = ko.observable(false);
	this.AddTollLinkVisible = ko.observable(false);

	// Set message of Inbound phone number
	// Message of Inbound Phone Number
	this.MsgInboundNumber = ko.observable();


	// Class to represent a row in the table phone
	function LocalPhoneItem(_id, _localPhoneNumber, _allowInput, _showNumber) {
		this.id = _id;
		this.localPhoneNumber = _localPhoneNumber;
		this.allowInput = _allowInput;
		this.showNumber = _showNumber;
	}
	function TollPhoneItem(_id, _tollPhoneNumber, _allowInput, _showNumber) {
		this.id = _id;
		this.tollPhoneNumber = _tollPhoneNumber;
		this.allowInput = _allowInput;
		this.showNumber = _showNumber;
	}

	// Initialization
	if (data.IsAccountFreeTrial) {  // Free Trial
		if (data.ListInboundPhone.length > 0) { // Show list inbound phones got success in the view
			for (var i = 0; i < data.ListInboundPhone.length; i++) {
				this.localPhones.push(new LocalPhoneItem(iLocalPhone.toString(), data.ListInboundPhone[i], false, true));
				iLocalPhone++;
			}
		}

		if (data.ListTollFreePhone.length > 0) { // Show list toll free phones got success in the view
			for (var i = 0; i < data.ListTollFreePhone.length; i++) {
				this.tollPhones.push(new TollPhoneItem(iTollPhone.toString(), data.ListTollFreePhone[i], false, true));
				iTollPhone++;
			}
		}
		if (data.IsDialIq && canAddPhone(this.localPhones(), this.tollPhones())) {  // If have seat for get then show Get inbound button, else not
			this.localPhones.push(new LocalPhoneItem(iLocalPhone.toString(), "waiting", true, false));
			this.tollPhones.push(new TollPhoneItem(iTollPhone.toString(), "waiting", true, false));
		}
		this.MsgInboundNumber("Set up an inbound phone number as either local or toll free.  During the free trial, you can request up to 3 phone numbers.  Following the free trial, the cost of inbound phone numbers is $2.00 per number per month.");
	}
	else {  // Paid
		if (data.ListInboundPhone.length > 0) { // Show list inbound phones got success in the view
			for (var i = 0; i < data.ListInboundPhone.length; i++) {
				this.localPhones.push(new LocalPhoneItem(iLocalPhone.toString(), data.ListInboundPhone[i], false, true));
				iLocalPhone++;
			}
		}

		if (data.ListTollFreePhone.length > 0) { // Show list toll free phones got success in the view
			for (var i = 0; i < data.ListTollFreePhone.length; i++) {
				this.tollPhones.push(new TollPhoneItem(iTollPhone.toString(), data.ListTollFreePhone[i], false, true));
				iTollPhone++;
			}
		}
		if (data.IsDialIq) {    // If the user bought Dial Iq then show Get inbound button
			this.localPhones.push(new LocalPhoneItem(iLocalPhone.toString(), "waiting", true, false));
			this.tollPhones.push(new TollPhoneItem(iTollPhone.toString(), "waiting", true, false));
		}
		this.MsgInboundNumber("Set up an inbound phone number as either local or toll free.  The cost of inbound phone numbers is $2.00 per number per month.");
	}

	this.AddLocalPhoneLink = function () {
		iLocalPhone++;
		this.localPhones.push(new LocalPhoneItem(iLocalPhone.toString(), "waiting", true, false));
		getLeadModel.AddLocalLinkVisible(false);
	};
	this.AddTollPhoneLink = function () {
		iTollPhone++;
		this.tollPhones.push(new TollPhoneItem(iTollPhone.toString(), "waiting", true, false));
		getLeadModel.AddTollLinkVisible(false);
	};

	this.OnKeyUp = function (phone, event) {
		var inputIdCurrent = '#iptAreaCode' + phone.id;
		var getNumBtnIdCurrent = '#get_number_local' + phone.id;
		if (($(inputIdCurrent).val().length == 3) &&
			(validateAreaCode($(inputIdCurrent).val()))) {
			// Enable Get number button
			getLeadModel.canGetLocal(true)
			$(getNumBtnIdCurrent).removeClass("btn-getnumber-gray");
			$(getNumBtnIdCurrent).removeClass("btn-getnumber-blue");
			$(getNumBtnIdCurrent).addClass("btn-getnumber-blue");
		}
		else {
			getLeadModel.canGetLocal(false);
			$(getNumBtnIdCurrent).removeClass("btn-getnumber-gray");
			$(getNumBtnIdCurrent).removeClass("btn-getnumber-blue");
			$(getNumBtnIdCurrent).addClass("btn-getnumber-gray");
		}
	}

	function canAddPhone(listLocal, listToll) {
		if (!data.IsAccountFreeTrial) { // Non free trial
			return true;
		}
		else {  // Free trial
			var localLength = listLocal.length;
			var tollLength = listToll.length;

			var localWait = 0;
			var tollWait = 0;

			for (var i = 0; i < localLength; i++) {
				if (listLocal[i].localPhoneNumber == "waiting") {
					localWait++;
				}
			}
			for (var i = 0; i < tollLength; i++) {
				if (listToll[i].tollPhoneNumber == "waiting") {
					tollWait++;
				}
			}

			var localCount = localLength - localWait;
			var tollCount = tollLength - tollWait;

			return ((localCount + tollCount) < 3) ? true : false;
		}
	}

	///////////////////////////// EVENTS //////////////////////////////
	this.GetNumberLocal = function (phone) {
		if (getLeadModel.canGetLocal()) {
			var areaCodeId = '#iptAreaCode' + phone.id;
			var areaCode = $(areaCodeId).val();
			var dataPost = { "areaCode": areaCode };
			var urlPost = "/SetUpWizard/GetInboundPhone";
			openProcess();

			$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
				success: function (returnData, textStatus, jqXHR) {
					if (returnData.Error == undefined || returnData.Error == null) {
						if (returnData != "") {     // Non limit phone numbers
							if (validateInboundPhone(returnData)) {
								phone.localPhoneNumber = returnData;
								phone.allowInput = false;
								phone.showNumber = true;

								refreshLocalList();
								// Check limit phones number
								if (canAddPhone(getLeadModel.localPhones(), getLeadModel.tollPhones())) {  // Can get continous
									getLeadModel.AddLocalLinkVisible(true);
								}
								else {  // Can't get continous => Remove Link add phone
									ClearContent();
								}
								hideProcess();
							}
							else {
								hideProcess();
								showAlertPopup(returnData.toString(), '');
							}
						}
						else {  // Limited phone numbers
							$("#areaCodeHidden").val(areaCode);
							$("#phoneIdHidden").val(phone.id);
							$('#addPhoneAlert').showPopup({
								width: 470
							});
							$('#fancybox-overlay').show();
						}
					}
					else {
						hideProcess();
						showPopupError();
					}
				},
				error: function (xhr, status, error) {
					hideProcess();
					showPopupError();
				}
			}); // End ajax post
		}
	};

	this.GetNumberToll = function (phone) {

		var dataPost = {};
		var urlPost = "/SetUpWizard/GetTollFreePhone";
		openProcess();

		$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
			success: function (returnData, textStatus, jqXHR) {
				if (returnData.Error == undefined || returnData.Error == null) {
					if (returnData != "") {     // Non limit phone numbers
						if (validateInboundPhone(returnData)) {
							phone.tollPhoneNumber = returnData;
							phone.allowInput = false;
							phone.showNumber = true;

							refreshTollList();
							// Check limit phones number
							if (canAddPhone(getLeadModel.localPhones(), getLeadModel.tollPhones())) {
								getLeadModel.AddTollLinkVisible(true);
							}
							else {
								ClearContent();
							}
							hideProcess();
						}
						else {
							hideProcess();
							showAlertPopup(returnData.toString(), '');
						}
					}
					else {  // Limited phone numbers
						$("#areaCodeHidden").val("");
						$("#phoneIdHidden").val(phone.id);
						$('#addPhoneAlert').showPopup({
							width: 470
						});
						$('#fancybox-overlay').show();
					}
				}
				else {
					hideProcess();
					showPopupError();
				}
			},
			error: function (xhr, status, error) {
				hideProcess();
				showPopupError();
			}
		}); // End ajax post
	};

	this.AutoBuyInboundPhoneNumber = function () {
		var areaCodeHidden = $("#areaCodeHidden").val();  // areaCodeHidden is number if Get Local phone and is blank if Get toll free
		var phoneIdHidden = $("#phoneIdHidden").val();
		//console.log("areaCodeHidden:" + areaCodeHidden);
		//console.log("phoneIdHidden:" + phoneIdHidden);

		closeAddPhoneAlert();

		// Json Get function to retrive data from server
		openProcess();

		var dataPost = { "areaCode": areaCodeHidden };
		var urlPost = "/SetUpWizard/AutoBuyInboundPhoneNumber";

		$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
			success: function (returnData, textStatus, jqXHR) {
				if (returnData.Error == undefined || returnData.Error == null) {
					if (validateInboundPhone(returnData)) {
						hideProcess();
						if (areaCodeHidden.toString() != "") {  // Case Local phone
							var list = getLeadModel.localPhones();
							getLeadModel.localPhones([]);

							for (var i = 0; i < list.length; i++) {
								if (list[i].id == phoneIdHidden) {
									list[i].localPhoneNumber = returnData;
									list[i].allowInput = false;
									list[i].showNumber = true;
									break;
								}
							}
							getLeadModel.localPhones(list);
							getLeadModel.AddLocalLinkVisible(true);
						}
						else {  // Case Toll Free
							var list = getLeadModel.tollPhones();
							getLeadModel.tollPhones([]);

							for (var i = 0; i < list.length; i++) {
								if (list[i].id == phoneIdHidden) {
									list[i].tollPhoneNumber = returnData;
									list[i].allowInput = false;
									list[i].showNumber = true;
									break;
								}
							}
							getLeadModel.tollPhones(list);
							getLeadModel.AddTollLinkVisible(true);
						}

					}
					else {
						hideProcess();
						showAlertPopup(returnData.toString(), '');
					}
				}
				else {
					hideProcess();
					showPopupError();
				}
			},
			error: function (xhr, status, error) {
				hideProcess();
				showPopupError();
			}
		}); // End ajax post
	};

	// Refresh list
	function refreshLocalList() {
		var list = getLeadModel.localPhones();
		getLeadModel.localPhones([]);
		getLeadModel.localPhones(list);
	};
	function refreshTollList() {
		var list = getLeadModel.tollPhones();
		getLeadModel.tollPhones([]);
		getLeadModel.tollPhones(list);
	};

	function isWaitingGetLocal() {
		var localLength = getLeadModel.localPhones().length;
		var listLocal = getLeadModel.localPhones();

		for (var i = 0; i < localLength; i++) {
			if (listLocal[i].localPhoneNumber == "waiting") {
				return true;
			}
		}
		return false;
	};
	function isWaitingGetToll() {
		var tollLength = getLeadModel.tollPhones().length;
		var listToll = getLeadModel.tollPhones();

		for (var i = 0; i < tollLength; i++) {
			if (listToll[i].tollPhoneNumber == "waiting") {
				return true;
			}
		}
		return false;
	};

	function ClearContent() {
		getLeadModel.AddLocalLinkVisible(false);
		getLeadModel.AddTollLinkVisible(false);

		// Remove all waiting items
		var localLength = getLeadModel.localPhones().length;
		var tollLength = getLeadModel.tollPhones().length;
		var listLocal = getLeadModel.localPhones();
		var listToll = getLeadModel.tollPhones();

		for (var i = 0; i < localLength; i++) {
			if (listLocal[i].localPhoneNumber == "waiting") {
				listLocal.splice(i, 1);
			}
		}
		for (var i = 0; i < tollLength; i++) {
			if (listToll[i].tollPhoneNumber == "waiting") {
				listToll.splice(i, 1);
			}
		}
		getLeadModel.localPhones(listLocal);
		getLeadModel.tollPhones(listToll);
	}

	//************************* TAB4: CONNECT A WEBFORM  *****************************//

	this.showSuccess = ko.observable(false);
	this.showEmailMessage = ko.observable(false);
	this.ErrorEmailMessage = ko.observable("xxx");

	this.SendEmailButton = function () {
		var emailListInputted = $('#iptEmailInput').val();
		if (emailListInputted.length > 0) {
			var emailSendList = emailListInputted.split(",");

			// Send list email
			if (validateListEmail(emailSendList)) {

				$('#iptEmailInput').val(formatListEmail(emailSendList));
				ConnectWebform(formatListEmail(emailSendList));
			}
			else {
				getLeadModel.ErrorEmailMessage("Enter a valid email");
				getLeadModel.showEmailMessage(true);
				getLeadModel.showSuccess(false);
			}
		}
		else {
			getLeadModel.ErrorEmailMessage("Email is required");
			getLeadModel.showEmailMessage(true);
		}
	};

	this.SentEmailSuccessClass = ko.computed(function () {
		return (this.showSuccess()) ? "info-msg" : "error-hide";
	}, this);

	this.ErrorEmailClass = ko.computed(function () {
		return (this.showEmailMessage()) ? "error-show" : "error-hide";
	}, this);


	//********************** Navigation  ************************//
	this.BackButton = function () {
		this.DisplayThreeStep(false);
		yourTeamModel.DisplayFirstStep(false);
		chooseEmailModel.DisplaySecondStep(true);
		window.scrollTo(0, 0);
	};

	this.NextButton = function () {
		AssignCookieCompleteSetup();
		ConnectToVideoTourModal();
	};

	this.FinishLaterButton = function () {
		ConnectToVideoTourModal();
	};

	function AssignCookieCompleteSetup() {
		// Save cookie: completeSetup = true
		$.cookie("completesetup", "true", { path: '/', expires: 365 });
	}

	function ConnectToVideoTourModal() {
		if (!$.cookie("VideoTour_DontShowAgain_" + $.trim($("#EmailOfCurrentUser").text()) )) {
			window.location = "/SetUpWizard/SetUpWizardWelcome";
		}
		else {
			window.location = "/Dashboard/";
		}
	}

	// Extend view model with import lead
	// Date: 11/21/2012

	/*-----------------------------------------------------VIEW MODELS ------------------------------------------------*/
	// Step 1
	this.DisplayFirstView = ko.observable(true);
	// End Step 1

	// Step 2
	this.DisplayHelp = ko.observable(false);
	this.GoBackStep1 = function () {
		getLeadModel.DisplayFirstView(true);
		getLeadModel.DisplayHelp(false);
		getLeadModel.DisplaySecondView(false);
		getLeadModel.DisplayThirdView(false);

	};

	this.GoToMatch = function () {
		var ManualImportId = $('#StoreManualID').val();

		$.fancybox($('#popup-processing-getmapping'),
		{
			padding: 0,
			closeBtn: false,
			helpers: {
				overlay: {
					opacity: 0.8,
					css: { 'background-color': '#11619d' },
					closeClick: false
				}
			}
		});

		if (ManualImportId != undefined) {

			var dataPost = { "manualImportID": ManualImportId };


			$.ajax({
				type: "POST",
				url: "/EnhancedManualImport/GetMapping",
				data: dataPost,
				dataType: "json",
				success: function (ModelFields, textStatus, jqXHR) {
					$.fancybox.close();
					if ((ModelFields != "") && (ModelFields.Mapping.Columns != null)) {
						getLeadModel.DisplayFirstView(false);
						getLeadModel.DisplayHelp(false);

						getLeadModel.AllFieldGroups(ModelFields.Mapping.AllFieldGroups);

						getLeadModel.DisplaySecondView(true);
						getLeadModel.DisplayThirdView(false);
						// build array with items
						var items = [];
						var firstUnmappedColumnName = "";
						var count = 0;
						var unmappedCount = 0;
						//found unmapped column
						for (var i = 0; i < ModelFields.Mapping.Columns.length; i++) {
							var item = ModelFields.Mapping.Columns[i];
							if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
								firstUnmappedColumnName = item.ColumnName;
								break;
							}
						}

						for (var i = 0; i < ModelFields.Mapping.Columns.length; i++) {
							var item = ModelFields.Mapping.Columns[i];
							var newItem = {
								ColumnName: item.ColumnName,
								IsIgnored: item.IsIgnored,
								PossibleGroups: item.PossibleGroups,
								PossibleFieldsInOrder: item.PossibleFieldsInOrder,
								MappedField: item.MappedField,
								IsActive: item.ColumnName == firstUnmappedColumnName ? true : false
							};
							items.push(newItem);
							if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
								unmappedCount = unmappedCount + 1;
							}
						}
						getLeadModel.MappingColumns(items);
						getLeadModel.TotalMatchedHeaders(ModelFields.Mapping.Columns.length - unmappedCount);
						getLeadModel.TotalHeaders(ModelFields.Mapping.Columns.length);
						getLeadModel.UpdateView();
					}
					else {
						showPopupError();
					}
				},
				error: function (xhr, status, error) {
					$.fancybox.close();
					showCustomError(eval("(" + xhr.responseText + ")"));
				}

			});
		};
	};

	// End Step 2

	// Step 3
	this.DisplaySecondView = ko.observable(false);

	this.TotalHeaders = ko.observable(40);

	this.HeaderText = ko.computed(function () {
		if (this.TotalHeaders() > 1) {
			return "headers matched";
		}
		else {
			return "header matched";
		}

	}, this);

	this.TotalMatchedHeaders = ko.observable(17);
	this.ProgressValue = ko.observable('0%');
	this.CheckProgressValue = ko.computed(function () {
		this.ProgressValue((100 * this.TotalMatchedHeaders() / this.TotalHeaders()) + '%');
	}, this);
	this.MappingColumns = ko.observableArray();

	this.AllFieldGroups = ko.observableArray();
	this.DisplayedColumns = ko.observableArray();
	this.DisplayedGroups = ko.observableArray();
	this.CurrentFieldGroups = ko.observableArray();
	this.CurrentFieldsInOrder = ko.observableArray();

	this.ViewType = "All"; //All, Unmatched
	this.SearchFieldText = ko.observable("Search Header Names");
	this.FilterMode = ko.observable("DataType"); // DataType, All
	this.ActiveColumn = null;
	this.LastMappedColumns = "";
	this.Initialized = false;
	this.AllColumnsMapped = ko.observable(false);

	this.EnableSearch = ko.computed(function () {
		if (this.DisplayedGroups().length > 0 || (this.TotalHeaders() - this.TotalMatchedHeaders()) > 0) {

			return true;
		}
		else {

			return false;
		}

	}, this);


	this.UpdateView = function () {
		var unmappedCount = 0;
		this.Initialized = true;
		var firstUnmappedColumnName = "";
		this.DisplayedColumns.removeAll();
		this.DisplayedGroups.removeAll();
		$(".i-matched").remove();
		$(".i-matched1").remove();
		var foundFirstItem = false;


		if (this.ViewType == "All") {
			for (var i = 0; i < this.MappingColumns().length; i++) {
				var item = this.MappingColumns()[i];
				if (item.IsIgnored == false) {
					if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
						unmappedCount = unmappedCount + 1;
					}
					var newItem = {
						ColumnName: item.ColumnName,
						IsIgnored: item.IsIgnored,
						PossibleGroups: item.PossibleGroups,
						PossibleFieldsInOrder: item.PossibleFieldsInOrder,
						MappedField: item.MappedField,
						IsActive: false
					};
					if ((typeof (item.MappedField) == "undefined" || item.MappedField == null) && (!foundFirstItem) && (item.IsIgnored != true)) {
						firstUnmappedColumnName = item.ColumnName;
						foundFirstItem = true;
						newItem.IsActive = true;
						this.ActiveColumn = newItem;
					}
					this.DisplayedColumns.push(newItem);
				}
			}
			if (!foundFirstItem) {
				this.ActiveColumn = null;
				this.AllColumnsMapped(true);
			}
		}
		else {
			for (var i = 0; i < this.MappingColumns().length; i++) {
				var item = this.MappingColumns()[i];
				if (item.IsIgnored == false) {
					if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
						unmappedCount = unmappedCount + 1;
						var newItem = {
							ColumnName: item.ColumnName,
							IsIgnored: item.IsIgnored,
							PossibleGroups: item.PossibleGroups,
							PossibleFieldsInOrder: item.PossibleFieldsInOrder,
							MappedField: item.MappedField,
							IsActive: false
						};
						if (!foundFirstItem) {
							newItem.IsActive = true;
							firstUnmappedColumnName = item.ColumnName;
							foundFirstItem = true;
							newItem.IsActive = true;
							this.ActiveColumn = newItem;
						}
						this.DisplayedColumns.push(newItem);
					}
				}
			}
			if (!foundFirstItem) {
				this.ActiveColumn = null;
				this.AllColumnsMapped(true);
			}
		}
		if (this.ActiveColumn == null) {
			getLeadModel.TotalMatchedHeaders(this.MappingColumns().length - unmappedCount);
			document.getElementById("NextToStep3").setAttribute("class", "btn btn-next-blue right");
			//All fields are mapped, nothing will be showed in the right panel
			return;
		}
		else {
			document.getElementById("NextToStep3").setAttribute("class", "btn btn-next-gray right");
		}

		if ((this.FilterMode() == "DataType")
			&& ((this.SearchFieldText() == "") || (this.SearchFieldText() == "Search Header Names"))) {
			this.CurrentFieldGroups(clone(this.ActiveColumn.PossibleGroups));
			this.CurrentFieldsInOrder(clone(this.ActiveColumn.PossibleFieldsInOrder));
		}
		else {
			this.CurrentFieldGroups(clone(this.AllFieldGroups()));
		}
		getLeadModel.TotalMatchedHeaders(this.MappingColumns().length - unmappedCount);
		this.FilterFieldGroups();
		this.DisplayedGroups(this.CurrentFieldGroups());
		if (this.ActiveColumn != "undefined" && this.ActiveColumn != null)
			document.getElementById(this.ActiveColumn.ColumnName).scrollIntoView(true);

	};


	this.FilterFieldGroups = function () {
		if ((this.FilterMode() == "DataType") && ((this.SearchFieldText() == "") || (this.SearchFieldText() == "Search Header Names"))) {
			for (var i = this.CurrentFieldsInOrder().length - 1; i > -1; i--) {
				if (this.CurrentFieldsInOrder()[i].IsUsed == "true") {
					this.CurrentFieldsInOrder().splice(i, 1);
				}
			}
			if (this.CurrentFieldsInOrder().length > 10) {
				this.CurrentFieldsInOrder().splice(10, this.CurrentFieldsInOrder().length - 10);
			}

			for (var i = this.CurrentFieldGroups().length - 1; i > -1; i--) {
				var groupItem = this.CurrentFieldGroups()[i];
				var groupHasChildren = false;
				if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
					for (var j = groupItem.Fields.length - 1; j > -1; j--) {
						var fieldItem = groupItem.Fields[j];
						if (fieldItem.IsUsed == true) {
							groupItem.Fields.splice(j, 1);
						}
						else {
							var found = false;
							for (var k = 0; k < this.CurrentFieldsInOrder().length; k++) {
								var orderedFI = this.CurrentFieldsInOrder()[k];
								if (fieldItem.FieldId == orderedFI.FieldId) {
									found = true;
									break;
								}
							}
							if (found == false) {
								groupItem.Fields.splice(j, 1);
							}
						}
					}
					if (groupItem.Fields.length > 0) {
						groupHasChildren = true;
					}
				}
				if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
					for (var j = groupItem.Sections.length - 1; j > -1; j--) {
						var sectionItem = groupItem.Sections[j];
						for (var k = sectionItem.Fields.length - 1; k > -1; k--) {
							var fieldItem = sectionItem.Fields[k];
							if (fieldItem.IsUsed == true) {
								sectionItem.Fields.splice(k, 1);
							}
							else {
								var found = false;
								for (var l = 0; l < this.CurrentFieldsInOrder().length; l++) {
									var orderedFI = this.CurrentFieldsInOrder()[l];
									if (fieldItem.FieldId == orderedFI.FieldId) {
										found = true;
										break;
									}
								}
								if (found == false) {
									sectionItem.Fields.splice(k, 1);
								}
							}
						}
						if (sectionItem.Fields.length > 0) {
							groupHasChildren = true;
						}
						else {
							groupItem.Sections.splice(j, 1);
						}
					}
					if (groupItem.Sections.length == 0) {
						groupItem.Sections = null;
					}
				}
				if (groupHasChildren == false) {
					this.CurrentFieldGroups().splice(i, 1);
				}
			}
		}
		else {
			for (var i = this.CurrentFieldGroups().length - 1; i > -1; i--) {
				var groupItem = this.CurrentFieldGroups()[i];
				var groupHasChildren = false;
				if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
					for (var j = groupItem.Fields.length - 1; j > -1; j--) {
						var fieldItem = groupItem.Fields[j];
						if (fieldItem.IsUsed == true) {
							groupItem.Fields.splice(j, 1);
						}
						else {
							if ((this.SearchFieldText() != "") && (this.SearchFieldText() != "Search Header Names")) {
								if (fieldItem.FieldName.toLowerCase().indexOf(this.SearchFieldText().toLowerCase()) == -1) {
									groupItem.Fields.splice(j, 1);
								}
							}
						}
					}
					if (groupItem.Fields.length > 0) {
						groupHasChildren = true;
					}
				}
				if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
					for (var j = groupItem.Sections.length - 1; j > -1; j--) {
						var sectionItem = groupItem.Sections[j];
						for (var k = sectionItem.Fields.length - 1; k > -1; k--) {
							var fieldItem = sectionItem.Fields[k];
							if (fieldItem.IsUsed == true) {
								sectionItem.Fields.splice(k, 1);
							}
							else {
								if ((this.SearchFieldText() != "") && (this.SearchFieldText() != "Search Header Names")) {
									if (fieldItem.FieldName.toLowerCase().indexOf(this.SearchFieldText().toLowerCase()) == -1) {
										sectionItem.Fields.splice(k, 1);
									}
								}
							}
						}
						if (sectionItem.Fields.length > 0) {
							groupHasChildren = true;
						}
						else {
							groupItem.Sections.splice(j, 1);
						}
					}
					if (groupItem.Sections.length == 0) {
						groupItem.Sections = null;
					}
				}
				if (groupHasChildren == false) {
					this.CurrentFieldGroups().splice(i, 1);
				}
			}

		}
	}


	this.ViewAllFields = function () {
		this.FilterMode("All");
		this.SearchFieldText("");
		this.UpdateView();
		this.SearchFieldText("Search Header Names");
	};


	this.EnterHandler = function (getLeadModel, event) {
		if (event.keyCode == 13) {
			this.SearchFieldText($('#searchKeywordstep2').val());
			if ((this.SearchFieldText() != "Search Header Names") || (this.FilterMode() != "DataType")) {
				this.FilterMode("DataType");
				this.UpdateView();
			}
		}
		return true;
	}

	this.SearchFields = function () {
		if ((this.SearchFieldText() != "Search Header Names") || (this.FilterMode() != "DataType")) {
			this.FilterMode("DataType");

			this.UpdateView();

		}
		if (this.SearchFieldText() == "") {
			this.SearchFieldText("Search Header Names");

		}

	};

	this.GoBackHelp = function () {
		getLeadModel.DisplayFirstView(false);
		getLeadModel.DisplayHelp(true);
		getLeadModel.DisplaySecondView(false);
		getLeadModel.DisplayThirdView(false);
	};

	this.MatchColumn = function (fieldId, fieldName) {
		if ((fieldId == null) || (fieldId == 0)) return;
		if (this.ActiveColumn == null) return;
		// Update the column mappings
		for (var i = 0; i < this.MappingColumns().length; i++) {
			var columnItem = this.MappingColumns()[i];
			// Update the current column
			if (columnItem.ColumnName == this.ActiveColumn.ColumnName) {
				columnItem.MappedField = {
					FieldId: fieldId,
					FieldName: fieldName
				};
			}

			// update all possible fields of all columns to mark the dropped field as IsUsed
			var found = false;
			for (var j = 0; j < columnItem.PossibleGroups.length; j++) {
				var groupItem = columnItem.PossibleGroups[j];
				if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
					for (var k = 0; k < groupItem.Fields.length; k++) {
						var fieldItem = groupItem.Fields[k];
						if (fieldItem.FieldId == fieldId) {
							fieldItem.IsUsed = true;
							found = true;
							break;
						}
					}
				}
				if (found == true) {
					break;
				}
				if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
					for (var k = 0; k < groupItem.Sections.length; k++) {
						var sectionItem = groupItem.Sections[k];
						for (var h = 0; h < sectionItem.Fields.length; h++) {
							var fieldItem = sectionItem.Fields[h];
							if (fieldItem.FieldId == fieldId) {
								fieldItem.IsUsed = true;
								found = true;
								break;
							}
						}
						if (found == true) {
							break;
						}
					}
				}
				if (found == true) {
					break;
				}
			}
		}

		// Update the all fields to mark the dropped field as IsUsed
		var found1 = false;
		for (var j = 0; j < this.AllFieldGroups().length; j++) {
			var groupItem = this.AllFieldGroups()[j];
			if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
				for (var k = 0; k < groupItem.Fields.length; k++) {
					var fieldItem = groupItem.Fields[k];
					if (fieldItem.FieldId == fieldId) {
						fieldItem.IsUsed = true;
						found1 = true;
						break;
					}
				}
			}
			if (found1 == true) {
				break;
			}
			if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
				for (var k = 0; k < groupItem.Sections.length; k++) {
					var sectionItem = groupItem.Sections[k];
					for (var h = 0; h < sectionItem.Fields.length; h++) {
						var fieldItem = sectionItem.Fields[h];
						if (fieldItem.FieldId == fieldId) {
							fieldItem.IsUsed = true;
							found1 = true;
							break;
						}
					}
					if (found1 == true) {
						break;
					}
				}
			}
			if (found1 == true) {
				break;
			}
		}

	};

	this.x_OutColumn = function (data) {
		getLeadModel.UnMatchColumn(data.ColumnName, true);
		getLeadModel.UpdateView();
	};

	this.UnMatchColumn = function (columnName, ignore) {

		// Update the column mappings
		var fieldId = 0;
		for (var i = 0; i < this.MappingColumns().length; i++) {
			var columnItem = this.MappingColumns()[i];
			// Update the current column
			if (columnItem.ColumnName == columnName) {
				if ((typeof (columnItem.MappedField) != "undefined") && (columnItem.MappedField != null)) {
					fieldId = columnItem.MappedField.FieldId;
					columnItem.MappedField = null;
				}
				if (ignore == true) {
					columnItem.IsIgnored = true;
				}
				else {
					columnItem.IsIgnored = false;
				}
				break;
			}
		}

		if (fieldId == 0) return;

		for (var i = 0; i < this.MappingColumns().length; i++) {
			var columnItem = this.MappingColumns()[i];
			// update all possible fields of all columns to mark the undropped field as IsUnUsed
			var found = false;
			for (var j = 0; j < columnItem.PossibleGroups.length; j++) {
				var groupItem = columnItem.PossibleGroups[j];
				if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
					for (var k = 0; k < groupItem.Fields.length; k++) {
						var fieldItem = groupItem.Fields[k];
						if (fieldItem.FieldId == fieldId) {
							fieldItem.IsUsed = false;
							found = true;
							break;
						}
					}
				}
				if (found == true) {
					break;
				}
				if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
					for (var k = 0; k < groupItem.Sections.length; k++) {
						var sectionItem = groupItem.Sections[k];
						for (var h = 0; h < sectionItem.Fields.length; h++) {
							var fieldItem = sectionItem.Fields[h];
							if (fieldItem.FieldId == fieldId) {
								fieldItem.IsUsed = false;
								found = true;
								break;
							}
						}
						if (found == true) {
							break;
						}
					}
				}
				if (found == true) {
					break;
				}
			}
		}

		// Update the all fields to mark the dropped field as IsUnUsed
		var found1 = false;
		for (var j = 0; j < this.AllFieldGroups().length; j++) {
			var groupItem = this.AllFieldGroups()[j];
			if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
				for (var k = 0; k < groupItem.Fields.length; k++) {
					var fieldItem = groupItem.Fields[k];
					if (fieldItem.FieldId == fieldId) {
						fieldItem.IsUsed = false;
						found1 = true;
						break;
					}
				}
			}
			if (found1 == true) {
				break;
			}
			if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
				for (var k = 0; k < groupItem.Sections.length; k++) {
					var sectionItem = groupItem.Sections[k];
					for (var h = 0; h < sectionItem.Fields.length; h++) {
						var fieldItem = sectionItem.Fields[h];
						if (fieldItem.FieldId == fieldId) {
							fieldItem.IsUsed = false;
							found1 = true;
							break;
						}
					}
					if (found1 == true) {
						break;
					}
				}
			}
			if (found1 == true) {
				break;
			}
		}

	};
	this.GoToDataCorrection = function () {
		if (this.AllColumnsMapped() == false) return;
		var ManualImportId = $('#StoreManualID').val();
		var columnSeparator = ";$;";
		var propertySeparator = ";#;";
		var mappingSettings = "";

		for (var i = 0; i < this.MappingColumns().length; i++) {
			var mappingItem = this.MappingColumns()[i];
			if (i == 0) {
				mappingSettings = mappingItem.ColumnName
					+ propertySeparator
					+ mappingItem.IsIgnored
					+ propertySeparator
					+ ((mappingItem.MappedField == null) ? 0 : mappingItem.MappedField.FieldId);
			}
			else {
				mappingSettings = mappingSettings
					+ columnSeparator
					+ mappingItem.ColumnName
					+ propertySeparator
					+ mappingItem.IsIgnored
					+ propertySeparator
					+ ((mappingItem.MappedField == null) ? 0 : mappingItem.MappedField.FieldId);
			}
		}
		init_review_import();
		var dataPost = { "manualImportID": ManualImportId, "MappingSettings": mappingSettings };

		$.ajax({
			type: "POST",
			url: "/EnhancedManualImport/SaveMappingAndGetDataErrors",
			data: dataPost,
			dataType: "json",
			success: function (dataErrors, textStatus, jqXHR) {

				$.fancybox.close();
				$('#DoNotImportLeadswithErrors').removeAttr("jcf-hidden");
				$('#DoNotImportLeadswithErrors').attr("class", "jcf-select");

				if (dataErrors.IsError == true) {
					showCustomError(dataErrors.ErrorMessage);
				}
				else {
					//Update IsIgnored in CellModel
					var _ErrorRows = dataErrors.DataError.ErrorRows;
					var _ColumnHeaders = dataErrors.DataError.ColumnHeaders;
					var countErrorRows = _ErrorRows.length;
					var countColumnHeaders = _ColumnHeaders.length;
					if (countColumnHeaders > 0) {
						for (var i = 0; i < countColumnHeaders; i++) {
							if (countErrorRows > 0) {
								for (var j = 0; j < countErrorRows; j++) {
									if (_ColumnHeaders[i].IsIgnored) {
										_ErrorRows[j].Cells[i].IsIgnored = true;
									}
									_ErrorRows[j].Cells[i].CellID = i + '-' + j;
									_ErrorRows[j].Cells[i].IsDone = false;

									//set class for cell
									if (_ErrorRows[j].Cells[i].IsDone) {
										_ErrorRows[j].Cells[i].ClassName = "col1 done";
									}
									else if (_ErrorRows[j].Cells[i].IsError) {
										_ErrorRows[j].Cells[i].ClassName = "col1 error";
									}
									else {
										_ErrorRows[j].Cells[i].ClassName = "col1";
									}
								}
							}
						}
					}
					if (countErrorRows > 0) {
						var displayError = false;
						for (var i = 0; i < _ErrorRows[0].Cells.length; i++) {
							if (!_ErrorRows[0].Cells[i].IsIgnored) {
								if ((_ErrorRows[0].Cells[i].IsError == true) || (_ErrorRows[0].Cells[i].Value == "")) {
									displayError = true;
									break;
								}
							}
						}
						getLeadModel.HasErrorsToDisplay(displayError);
					}
					else {
						getLeadModel.HasErrorsToDisplay(false);
					}
					getLeadModel.DisplayFirstView(false);
					getLeadModel.DisplayHelp(false);
					getLeadModel.DisplaySecondView(false);
					getLeadModel.DisplayThirdView(true);

					getLeadModel.ColumnHeaders(dataErrors.DataError.ColumnHeaders);
					getLeadModel.ErrorRows(_ErrorRows);
				}
			},
			error: function (xhr, status, error) {
				$.fancybox.close();
				showCustomError(eval("(" + xhr.responseText + ")"));
			}

		});

	};

	// End Step 3

	// Step 4
	this.titleReviewandImport = ko.observable('We have identified some errors and missing data in your file.');
	this.DisplayThirdView = ko.observable(false);
	this.ColumnHeaders = ko.observableArray([]);
	this.DisplayColumnHeaders = ko.observableArray([]);
	this.ErrorRows = ko.observableArray([]);
	this.DisplayErrorRows = ko.observableArray([]);
	this.HasErrorsToDisplay = ko.observable();

	this.Edit = function (data) {
		var idcell = data.CellID;
		$('#' + idcell).focus();
		$('.anchor .moreoptions').css("display", "none");

	}

	this.Cancel = function (data) {
		var _arrayId = data.CellID.split('-');
		var _row = _arrayId[1];
		var _cell = _arrayId[0];
		var _ArrayErrorRows = getLeadModel.ErrorRows();
		var _ArrayValidation = getLeadModel.ColumnHeaders()[_cell].RegularExpressions;
		var _IsRequired = getLeadModel.ColumnHeaders()[_cell].IsRequired;
		var _check = false;
		if (_IsRequired) {
			_check = false;
		}
		else {
			_check = true;
		}

		if (_check) {
			if (_IsRequired) {
				_ArrayErrorRows[_row].Cells[_cell].Value = "";
				_ArrayErrorRows[_row].Cells[_cell].IsDone = false;
				_ArrayErrorRows[_row].Cells[_cell].IsError = true;
				_ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";
				getLeadModel.ErrorRows([]);
				getLeadModel.ErrorRows(_ArrayErrorRows);
			}
			else {
				_ArrayErrorRows[_row].Cells[_cell].Value = "";
				_ArrayErrorRows[_row].Cells[_cell].IsDone = true;
				_ArrayErrorRows[_row].Cells[_cell].IsError = false;
				_ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 done";
				getLeadModel.ErrorRows([]);
				getLeadModel.ErrorRows(_ArrayErrorRows);
			}
		}
		else {
			_ArrayErrorRows[_row].Cells[_cell].Value = "";
			_ArrayErrorRows[_row].Cells[_cell].IsDone = false;
			_ArrayErrorRows[_row].Cells[_cell].IsError = true;
			_ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";
			getLeadModel.ErrorRows([]);
			getLeadModel.ErrorRows(_ArrayErrorRows);
		}
		var cellid = data.CellID;
		$('#' + cellid).focus();
		$('.anchor .moreoptions').css("display", "none");

	}

	this.EditDone = function (data) {
		if (data.ClassName == "col1 done") {
			var _value = data.Value;
			var _arrayId = data.CellID.split('-');
			var _row = _arrayId[1];
			var _cell = _arrayId[0];
			var _ArrayErrorRows = getLeadModel.ErrorRows();
			_ArrayErrorRows[_row].Cells[_cell].Value = "";
			//getLeadModel.ErrorRows([]);
			getLeadModel.ErrorRows(_ArrayErrorRows);
			getLeadModel.ErrorRows()[_row].Cells[_cell].Value = _value;
			var cellid = data.CellID;
			$('#' + cellid).focus();
			$('.anchor .moreoptions').css("display", "none");

			var idcell = data.CellID;
			$('#' + idcell + '-A').val(_value);

			var scrollleft = $("#gridview").scrollLeft();

			if (scrollleft > 0) {
				$('#scrollbar').css("display", "none");
			}
		}
	}

	this.BlurCell = function (data) {
		Update_Cell(data.Value, data.CellID);
	}

	this.CheckColumnHeaders = ko.computed(function () {
		var countColumnHeaders = this.ColumnHeaders().length;
		var computedDisplayColumns = clone(this.ColumnHeaders());
		var computedDisplayErrorRows = clone(this.ErrorRows());
		var countErrorRows = this.ErrorRows().length;
		this.DisplayErrorRows([]);
		for (var i = countColumnHeaders - 1; i > -1; i--) {
			var columnHeader = this.ColumnHeaders()[i];
			if (columnHeader.IsIgnored == true) {
				computedDisplayColumns.splice(i, 1);
				for (var j = 0; j < countErrorRows; j++) {
					var row = computedDisplayErrorRows[j];
					row.Cells.splice(i, 1);
				}
			}
		}
		this.DisplayColumnHeaders(computedDisplayColumns);
		this.DisplayErrorRows(computedDisplayErrorRows);

	}, this);

	//Count blank
	this.CountBlank = ko.computed(function () {
		var intBlank = 0;
		var intError = 0;
		var countErrorRows = this.ErrorRows().length;
		if (countErrorRows > 0) {
			for (var i = 0; i < countErrorRows; i++) {
				if (!this.ErrorRows()[i].IgnoreWhenImport) {
					for (var j = 0; j < this.ErrorRows()[i].Cells.length; j++) {
						if (!this.ErrorRows()[i].Cells[j].IsIgnored) {
							if (this.ErrorRows()[i].Cells[j].Value == "") {
								intBlank = intBlank + 1;
							}
						}
					}
				}
			}
		}
		return intBlank;
	}, this);


	// Count Errors
	this.CountError = ko.computed(function () {
		var intError = 0;
		var countErrorRows = this.ErrorRows().length;
		if (countErrorRows > 0) {
			for (var i = 0; i < countErrorRows; i++) {
				if (!this.ErrorRows()[i].IgnoreWhenImport) {
					for (var j = 0; j < this.ErrorRows()[i].Cells.length; j++) {
						if (!this.ErrorRows()[i].Cells[j].IsIgnored) {
							if (this.ErrorRows()[i].Cells[j].IsError == true) {
								intError = intError + 1;
							}
						}
					}
				}
			}
		}
		return intError;
	}, this);

	// Count Errors G2
	this.CountErrorG2 = ko.computed(function () {
		var intError = 0;
		var countErrorRows = this.ErrorRows().length;
		if (countErrorRows > 0) {
			for (var i = 0; i < countErrorRows; i++) {
				if (!this.ErrorRows()[i].IgnoreWhenImport) {
					if (this.ErrorRows()[i].Cells.length > 2) {
						for (var j = 2; j < this.ErrorRows()[i].Cells.length; j++) {
							if (!this.ErrorRows()[i].Cells[j].IsIgnored) {
								if (this.ErrorRows()[i].Cells[j].IsError == true) {
									intError = intError + 1;
								}
							}
						}
					}
				}
			}
		}
		return intError;
	}, this);

	//Set text for error
	this.txtCountError = ko.computed(function () {
		if (this.CountError() > 1) {

			if (this.CountBlank() == 0) {
				return "There are " + this.CountError() + " errors" + " and no blank fields in your file.";
			} if (this.CountBlank() == 1) {
				return "There are " + this.CountError() + " errors" + " and" + " blank field in your file.";
			}
			else {
				return "There are " + this.CountError() + " errors" + " and " + this.CountBlank() + " blank fields in your file.";
			}

		}
		else if (this.CountError() == 1) {
			if (this.CountBlank() == 0) {
				return "There is " + this.CountError() + " error" + " and no blank fields in your file.";
			} if (this.CountBlank() == 1) {
				return "There is " + this.CountError() + " error " + " and " + this.CountBlank() + " blank field in your file.";
			}
			else {
				return "There is " + this.CountError() + " error" + " and " + this.CountBlank() + " blank fields in your file.";
			}
		}
		else {

			if (this.CountBlank() == 0) {
				return "There are no errors " + "or missing data in your file.";
			} if (this.CountBlank() == 1) {
				return "There are no errors " + "and " + this.CountBlank() + " blank field in your file.";
			}
			else {
				return "There are no errors " + "and " + this.CountBlank() + " blank fields in your file.";
			}
		}

	}, this);

	//Set text for blank fields
	this.txtCountBlank = ko.computed(function () {
		if (this.CountBlank() != 1) {
			return "blank fields";
		}
		else {
			return "blank field";
		}

	}, this);

	//Set width for grid
	this.WidthGrid = ko.computed(function () {
		var _widthScroll = $('#gridview').width();
		var _heightScroll = $('#gridview').height();
		var _heightCell = 31;
		var _height = 32;
		var _width = 80;
		var _widthCell = 120;
		var countErrorRows = this.ErrorRows().length;
		var countColumnHeaders = this.ColumnHeaders().length;
		var HeaderNonXOut = this.ColumnHeaders().length;
		if (countColumnHeaders > 0) {
			for (var i = 0; i < countColumnHeaders; i++) {
				if (!this.ColumnHeaders()[i].IsIgnored) {
					_width = _width + _widthCell;
				}

			}
		}
		if (countColumnHeaders > 0) {
			for (var i = 0; i < countColumnHeaders; i++) {
				if (this.ColumnHeaders()[i].IsIgnored) {
					HeaderNonXOut = HeaderNonXOut - 1;
				}

			}
		}
		if (countErrorRows > 0) {
			for (var i = 0; i < countErrorRows; i++) {
				if (!this.ErrorRows()[i].IgnoreWhenImport) {
					_height = _height + _heightCell;
				}
			}
		}

		// scroll more errors


		var limit_number_column = parseInt(_widthScroll / 120);

		if ((HeaderNonXOut - 2) <= limit_number_column) {
			_width = _widthScroll;
		}
		else {
			_width = _width - 308 + HeaderNonXOut;
		}

		if (countErrorRows < 9 || (HeaderNonXOut - 2) <= limit_number_column) {
			$('#scrollbar').css("display", "none");
		}
		else {
			// Show errors count
			if (this.CountErrorG2() > 0) {
				$('#scrollbar').css("display", "block");
			}
			else {
				$('#scrollbar').css("display", "none");
			}
		}
		return _width.toString() + "px";
	}, this);

	//Check last rows display
	this.LastRowDisplay = ko.computed(function () {
		var _LastRowDisplay = -1;
		var countErrorRows = this.ErrorRows().length;
		if (countErrorRows > 0) {
			for (var i = countErrorRows - 1; i >= 0; i--) {
				if (!this.ErrorRows()[i].IgnoreWhenImport) {
					_LastRowDisplay = this.ErrorRows()[i].RowNumber;
					break;
				}
			}
		}
		return _LastRowDisplay;
	}, this);

	this.ShowSuggestionmsg = ko.computed(function () {
		if (this.HasErrorsToDisplay()) {
			return true;
		}
		else {
			return false;
		}

	}, this);

	this.ShowDeleteBtn = ko.computed(function () {
		if (this.HasErrorsToDisplay()) {
			return true;
		}
		else {
			return false;
		}

	}, this);

	//Check show error msg
	this.titleReviewandImport = ko.computed(function () {


		if (this.HasErrorsToDisplay()) {
			return "We have identified some errors and missing data in your file."

		}
		else {
			if (this.DisplayErrorRows().length >= 5) {
				return "Below is an abbreviated listing of the first 5 leads for you to review.";

			}
			else {
				if (this.DisplayErrorRows().length != 1)
					return "Below is a listing of " + this.DisplayErrorRows().length + " leads for you to review.";
				else
					return "Below is a listing of " + this.DisplayErrorRows().length + " lead for you to review.";
			}
		}


	}, this);

	//Delete row
	this.x_OutRow = function (data) {
		var _ArrayError = ko.utils.arrayFilter(getLeadModel.ErrorRows(), function (RowError) {
			if (RowError.RowNumber == data.RowNumber) {
				RowError.IgnoreWhenImport = true;
			}
			return true;
		});
		getLeadModel.ErrorRows(_ArrayError);
	};

	//Check show button next
	this.DoNotImportLeadswithErrors = ko.observable(false);
	this.attrNextButton = ko.observable("btn btn-importleads-gray right");
	this.enableNextButton = ko.computed(function () {
		if (this.DoNotImportLeadswithErrors()) {
			this.attrNextButton("btn btn-importleads-blue right");
			return true;
		}
		else {
			if (this.CountError() == 0) {
				this.attrNextButton("btn btn-importleads-blue right");
				return true;
			}
			else {
				this.attrNextButton("btn btn-importleads-gray right");
				return false;
			}
		}
	}, this);

	//Send data to server
	this.SendDataToServer = function () {
		if (this.enableNextButton()) {
			var ManualImportId = $('#StoreManualID').val();
			var session = $('#StoreSession').val();

			$.fancybox($('#popup-processing-senddatatoserver'),
			{
				padding: 0,
				closeBtn: false,
				helpers: {
					overlay: {
						opacity: 0.8,
						css: { 'background-color': '#11619d' },
						closeClick: false
					}
				}
			});


			var DoNotImportLeadswithErrors = this.DoNotImportLeadswithErrors();
			var hasError = false;
			if (this.HasErrorsToDisplay() == true) {
				for (var i = 0; i < this.ErrorRows().length; i++) {
					var rowData = { session: session, errorRow: this.ErrorRows()[i] };
					$.ajax({
						async: false,
						type: "POST",
						url: "/EnhancedManualImport/SendRowToServer",
						contentType: "application/json; charset=utf-8",
						dataType: "JSON",
						data: JSON.stringify(rowData),
						success: function (datareturn) {
							if (datareturn != '') {
								$.fancybox.close();
								showCustomError(datareturn);
								hasError = true;
							}
						},
						error: function (xhr, status, error) {
							// Boil the ASP.NET AJAX error down to JSON.
							var err = eval("(" + xhr.responseText + ")");
							$.fancybox.close();
							showCustomError(err);
							hasError = true;
						}
					});
					if (hasError == true) {
						break;
					}
				}
			}
			if (hasError == false) {
				var data = {
					session: session,
					manualImportID: ManualImportId,
					DoNotImportLeadswithErrors: DoNotImportLeadswithErrors
				};

				$.ajax({
					async: false,
					type: "POST",
					url: "/EnhancedManualImport/CommitSendDataToServer",
					contentType: "application/json; charset=utf-8",
					dataType: "JSON",
					data: JSON.stringify(data),
					success: function (datareturn) {
						$.fancybox.close();
						if (datareturn == '') {
							getLeadModel.DisplayFirstView(true);
							getLeadModel.DisplayHelp(false);
							getLeadModel.DisplaySecondView(false);
							getLeadModel.DisplayThirdView(false);
							DeleteUpload();
							$('#emifile_upload-button').removeAttr("uploadify-button btn disabled");
							$('#emifile_upload-button').attr("class", "uploadify-button btn btn-upload-leads");
						}
						else {
							showCustomError(datareturn);
						}
					},
					error: function (xhr, status, error) {
						// Boil the ASP.NET AJAX error down to JSON.
						var err = eval("(" + xhr.responseText + ")");
						$.fancybox.close();
						showCustomError(err);
					}
				});
			}
		}
	}

	this.GoBackToStepTwo = function () {
		getLeadModel.DisplayFirstView(false);
		getLeadModel.DisplayHelp(false);
		getLeadModel.DisplaySecondView(true);
		getLeadModel.DisplayThirdView(false);
	}

	//to set width for grid and handle for scrolling



	this.DisplayErrorMessages = ko.computed(function () {
		var cols = ko.utils.arrayFilter(this.ColumnHeaders(), function (option) {
			return option.IsIgnored != true;
		});
		return (this.CountBlank() > 0 || this.CountError() > 0) && (cols.length > 5);
	}, this);
}

$(document).ready(function () {

	var textDefault = getLeadModel.SearchFieldText();
	var currentSearchText = $('#searchKeywordstep2').val();
	var textDefault = "Search Header Names";
	$('#searchKeywordstep2').focus(function () {
		currentSearchText = $('#searchKeywordstep2').val();
		if ($(this).val() == textDefault) {
			$(this).val("");
		}
	});
	$('#searchKeywordstep2').blur(function () {
		if ((($(this).val() == null) || ($(this).val() == '')) && (currentSearchText == textDefault)) {
			$(this).val(textDefault);
		}
	});


	$('#gridview').scroll(function () {
		var scrollleft = $("#gridview").scrollLeft();
		if (scrollleft > 0) {
			$('#scrollbar').css("display", "none");
		}
		else if (getLeadModel.CountErrorG2() > 0) {
			$('#scrollbar').css("display", "block");
		}

	});


});
/*to use for dragging and dropping*/
ko.bindingHandlers.itemDrag =
{
	init: function (element, valueAccessor) {
		$(element).draggable({
			revert: "invalid",
			containment: '#wrapper',
			appendTo: 'body',
			helper: 'clone'
		});
	}
}
ko.bindingHandlers.itemDrop =
{
	init: function (element, valueAccessor) {
		$(element).droppable({
			accept: ".i-matched1",
			drop: function (event, ui) {
				var DragDataId = ui.draggable.find(".IdField").val();
				var DragFieldName = ui.draggable.find(".FieldName").text();
				getLeadModel.MatchColumn(DragDataId, DragFieldName);
				getLeadModel.SearchFieldText("Search Header Names");
				getLeadModel.UpdateView();
				ui.draggable.remove();
				$('.match-header').css("overflow", "auto");
				$('.panel').css("overflow", "auto");
				if (($("#searchKeywordstep2").is(":focus")) && ($('#searchKeywordstep2').val() == "Search Header Names")) {
					$('#searchKeywordstep2').val("");
				}
			}

		});
	}
}

ko.bindingHandlers.itemDropBack =
{
	init: function (element, valueAccessor) {
		$(element).droppable({
			accept: ".i-matched",
			drop: function (event, ui) {
				var HeaderName = ui.draggable.parent().find(".lb").text();
				getLeadModel.UnMatchColumn(HeaderName, false);
				getLeadModel.SearchFieldText("Search Header Names");
				getLeadModel.UpdateView();
				ui.draggable.remove();
				$('.match-header').css("overflow", "auto");
				$('.panel').css("overflow", "auto");
				if (($("#searchKeywordstep2").is(":focus")) && ($('#searchKeywordstep2').val() == "Search Header Names")) {
					$('#searchKeywordstep2').val("");
				}
			}

		});
	}
}
ko.bindingHandlers.itemDragBack =
{
	init: function (element, valueAccessor) {
		$(element).draggable({
			revert: 'invalid',
			containment: '#wrapper',
			start: function () {
				$('#matchrightside').css("z-index", "1000");
				$('.match-header').css("overflow", "visible");
				$('.panel').css("overflow", "visible");
				$('#matchrightside .i-matched').css("z-index", "100");
				$('#matchrightside .i-matched1').css("z-index", "100");
			},
			appendTo: '#matchrightside',
			helper: 'clone'
		});
	}
}
ko.bindingHandlers.griddropdown =
{
	init: function (element) {

		$(element).click(function () {
			$('#ImportLeadThirdStep .moreoptions').css("display", "none");
			$(element).parent().find('.moreoptions').css("display", "block");

		});
	}
}

ko.applyBindings(getLeadModel, document.getElementById("threeStep"));


function hideProcessBar() {
	//$('.fancybox-skin').hide();
	$('#fancybox-overlay').hide();
	$.fancybox.close();
}
